package swing.solutions.ours;

import java.awt.Color;
import java.awt.Dimension;
import java.text.DateFormat;
import java.util.Date;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;

public class SwingTableRendererSolution extends JFrame {
	class DateRenderer extends DefaultTableCellRenderer {
		DateFormat formatter;

		@Override
		public void setValue(Object value) {
			if (formatter == null) {
				formatter = DateFormat.getDateInstance();
			}
			String text = (value == null) ? "" : formatter.format(value);
			setText(text);
			setToolTipText("Date: " + text);
		}

	}

	class ColorRenderer extends DefaultTableCellRenderer {
		@Override
		public void setValue(Object color) {
			setBackground((Color) color);
		}
	}

	class MyTableModel extends AbstractTableModel {

		@Override
		public String getColumnName(int column) {
			return "Column" + column;
		}

		@Override
		public int getRowCount() {
			return 10;
		}

		@Override
		public int getColumnCount() {
			return 5;
		}

		@Override
		public boolean isCellEditable(int row, int col) {
			return true;
		}

		@Override
		public Object getValueAt(int rowIndex, int columnIndex) {
			if (columnIndex == 1) {
				return new Date();
			}
			if (columnIndex == 2) {
				return new Integer(rowIndex);
			}
			if (columnIndex == 3) {
				return new Boolean(true);
			}
			if (columnIndex == 4) {
				return Color.RED;
			}
			return rowIndex + "/" + columnIndex;
		}

		@Override
		public Class<?> getColumnClass(int c) {
			return getValueAt(0, c).getClass();
		}

	}

	public SwingTableRendererSolution() {
		setTitle("My Frame");
		setSize(400, 150);
		setLocationRelativeTo(null);
		JTable table = new JTable(new MyTableModel());
		table.setPreferredScrollableViewportSize(new Dimension(500, 70));
		table.setFillsViewportHeight(true);
		table.setDefaultRenderer(Date.class, new DateRenderer());
		table.setDefaultRenderer(Color.class, new ColorRenderer());
		JScrollPane scrollPane = new JScrollPane(table);
		add(scrollPane);
		pack();
		setVisible(true);
	}

	public static void main(String args[]) throws ClassNotFoundException,
			InstantiationException, IllegalAccessException,
			UnsupportedLookAndFeelException {
		UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
		new SwingTableRendererSolution();
	}

}
